﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ELab.ImageProcess;
using System.Drawing.Imaging;
namespace ELab.Message
{
    public class ScreenMessage : IScreenMessage
    {

        public ScreenMessage()
        {
        }

        public ScreenMessage(byte[] data)
        {
            if (data == null || data.Length < 5 || data[0] != (byte)MessageType.Screen)
                throw new Exception("Invalidate data bytes of Event message");

            byte[] lengBytes = new byte[] { data[1], data[2], data[3], data[4] };
            int length = BitConverter.ToInt32(lengBytes, 0);
            if (length != data.Length)
                throw new Exception("Invalidate data bytes of Event message");

            var body = data.Skip(5).Take(length - 1).ToArray();
            this.Screem = ImageExtensions.FromByte(body);
        }

        public MessageType Type
        {
            get { return MessageType.Screen; }
        }

        public System.Drawing.Image Screem { get; set; }

        public byte[] Data
        {
            get
            {
                var imgByte = (this.Screem == null ? new byte[0] : this.Screem.ToByteArray(ImageFormat.Jpeg));
                var data = new byte[] { (byte)this.Type, 0, 0, 0, 0 };
                data = data.Append<byte>(imgByte);

                //Update length of message
                var bytesLength = BitConverter.GetBytes(data.Length);
                bytesLength.CopyTo(data, 1);

                return data;
            }
        }
    }
}
